<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\News;
use think\db;

/**
 * 产品列管理
 *
 * @icon fa fa-circle-o
 */
class BydShop extends Backend
{

    /**
     * BydShop模型对象
     * @var \app\admin\model\BydShop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\BydShop;

        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("shopcate", $this->model->getShopList());
        $this->view->assign("stateList", $this->model->getStateList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['bydshopcategory', 'bydset'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看详情
     */
    public function detail($ids)
    {
        $row = $this->model->get($ids);
        $this->view->assign("row", $row);
//        $shop=\app\admin\model\BydShopOrder::where('id',$ids)->find();
        //        $data=explode(',', $shop['productid']);
        //        foreach ($data as $v){
        //            $find[]=\app\admin\model\BydShop::find($v);
        //        }

        //$this->view->assign("find", $find);
        return $this->view->fetch();
        return $ids;
    }
    public function getAccessToken()
    {
        $appId     = 'wx9e0259b9a3c39453';
        $secretId  = 'f243537b1fa08381293069d29c30f4da';
        $accessUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET';
        // $url = sprintf($accessUrl,$appId,$secretId);
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9e0259b9a3c39453&secret=f243537b1fa08381293069d29c30f4da';
        //print_r($url);die;
        $result = $this->https_request($url);
        $Result = json_decode($result, true);
        return $Result['access_token'];
        // return $Result;

    }
    /**
     * 生成url
     */
    public function xcxurl($data)
    {
        $ACCESS_TOKEN = $this->getAccessToken();
        $qcode        = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=$ACCESS_TOKEN";
        $param        = json_encode(array("path" => "pages/details/details", "query" => "id=$data"));
        $result       = $this->httpRequest($qcode, $param, "POST");

        return $result;

    }
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $param  = $this->request->post("pow/a");
            if ($params) {
//                print_r($param);
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result) {
                        $this->refreshSpecial($this->model->id, array(), $params['specials']); #$shopid, $origin, $new
                        $url=new News();
                        $addurl=$url->xcxurl($this->model->id,0);
                        if($addurl['errcode']==0){
                            $up=\app\admin\model\BydShop::where('id',$this->model->id)->update(['shopurl'=>$addurl['url_link']]);
                        }
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //  $cre = \app\admin\model\BydShop::where('name', $params['name'])->find();

//                     $add = new \app\admin\model\BydShopSpecial();
                    //                     $add->data([
                    //                         'shopid'    => $cre['id'],
                    //                         'spections' => $param['spections'],
                    //                         'xc_price'  => $param['xc_price'],
                    // //                        'image'=>$param['image']
                    //                     ]);
                    //                     $add->save();
                    //                     if ($param['state'] == 1) {
                    //                         if ($param['num'] > 1) {
                    //                             for ($i = 2; $i < $param['num'] + 1; $i++) {
                    //                                 $adds = new \app\admin\model\BydShopSpecial();
                    //                                 echo $i;
                    //                                 $valuep = 'xc_price' . $i;
                    //                                 $values = 'spections' . $i;
                    //                                 $adds->data([
                    //                                     'shopid'    => $cre['id'],
                    //                                     'spections' => $param[$valuep],
                    //                                     'xc_price'  => $param[$values],
                    //                                 ]);
                    //                                 $adds->save();
                    //                             }
                    //                         }
                    //                     }

                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 清除转义符

     */
    public function stripslashes_deep($value)
    {
        $value = is_array($value) ?

        array_map('stripslashes_deep', $value) :

        stripslashes($value);

        return $value;

    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $specials        = \app\admin\model\BydShopSpecial::where(["shopid" => $ids])->column("id as special_id,spections,xc_price,good_code");
        $row['specials'] = $this->getSpecialInfo($ids, $specials);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                $result = false;

                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    $this->refreshSpecial($ids, $specials, $params['specials']); #$shopid, $origin, $new
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 提取商品规格信息
     *
     * @param  integer $id [description]
     * @return [type]      [description]
     */
    private function getSpecialInfo($id = 0, $specials)
    {
        $temp = array();
        # 提取已有的商品规格， 不能带Key，并转为Json字符串
        if ($id) {
            foreach ($specials as $key => $value) {$temp[] = $value;}
        }
        return json_encode($temp);
    }

    /***
     * 更新商品规格
     * */
    private function refreshSpecial($shopid, $origin, $new)
    {
        #如果值不为空
        if ($new != '') {
            $specData = json_decode($new, true);
            if (!empty($specData)) {
                $originKeys = array_keys($origin);

                #更新存在的， 添加新的，删除去掉的
                foreach ($specData as $key => $value) {

                    # 原来有数据，新提交数据有对应ID， 更新规格
                    if (!empty($originKeys) && in_array($value['special_id'], $originKeys)) {
                        unset($origin[$value['special_id']]);

                        $tmpData = ["spections" => $value['spections'], 'xc_price' => $value['xc_price'],'good_code'=> $value['good_code'],'image'=> $value['image']];
                        \app\admin\model\BydShopSpecial::where(["id" => $value['special_id']])->update($tmpData);

                    } else {
                        $book = \app\admin\model\BydShopSpecial::create([
                            "spections" => $value['spections'],
                            'xc_price'  => $value['xc_price'],
                            'good_code'  => $value['good_code'],
                            'shopid'    => $shopid,
                            'image'    => $value['image'],
                        ]);
                    } #

                }
                #删除去掉的
                foreach ($origin as $key => $value) {
                    \app\admin\model\BydShopSpecial::where(['id' => $key, 'shopid' => $shopid])->delete();
                }
            }
        }
    }
}
